package com.raos.orderservice.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * 自定义服务注册实现（模拟spring cloud zookeeper 注册中心接口实现）
 *
 * @author raos
 * @emil 991207823@qq.com
 * @date 2022/9/6 21:19
 */
public class ZookeeperServiceRegistry implements ServiceRegistry {

    private CuratorFramework curatorFramework;
    private final String ip;
    private final String port;
    private final String serviceName;
    private final String basePath = "/raos-registry";

    public ZookeeperServiceRegistry(String serviceName, String ip, String port, String zkServer) {
        this.serviceName = serviceName;
        this.ip = ip;
        this.port = port;
        this.curatorFramework = CuratorFrameworkFactory.builder()
                .connectionTimeoutMs(20000)
                .connectString(zkServer)
                .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .build();
        curatorFramework.start();
    }

    @Override
    public void register() {
        // 服务名称
        String serviceNamePath = basePath + "/" + serviceName;
        try {
            if (curatorFramework.checkExists().forPath(serviceNamePath) == null) {
                // 创建持久化的节点，作为服务名称
                this.curatorFramework.create()
                        .creatingParentsIfNeeded()
                        .withMode(CreateMode.PERSISTENT)
                        .forPath(serviceNamePath);
            }
            String urlNode = curatorFramework.create()
                    .withMode(CreateMode.EPHEMERAL)
                    .forPath(serviceNamePath + "/" + ip + ":" + port);
            System.out.println("服务 " + urlNode + " 注册成功...");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}